package com.ruoyi.framework.web.service;

import com.ruoyi.common.constant.RoleConstants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.enums.DeptAncestors;
import com.ruoyi.common.enums.DeptType;
import com.ruoyi.common.enums.RoleIdEnum;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.system.domain.SysRoleDept;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 注册校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysRegisterService
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private ISysRoleService sysRoleDeptService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 注册
     */
    public String register(RegisterBody registerBody)
    {
        String msg = "",
                // "00 系统内置“ 、”01 个人用户“ 、”02 企业用户“
                userType = registerBody.getUserType(),
                // 企业名称
                deptName = registerBody.getDeptName(),
                // 联系电话
                phone = registerBody.getMobile(),
                // 联系邮箱
                email = registerBody.getEmail(),
                // 密码
                password = registerBody.getPassword(),
                // 用户名
                username= registerBody.getUsername();
        // 验证码开关
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
        }
        //用户信息
        SysUser sysUser = new SysUser();
        sysUser.setUserName(phone);
        sysUser.setPhonenumber(phone);
        sysUser.setEmail(email);
        sysUser.setUserType(userType);
        sysUser.setNickName(phone);
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        if (StringUtils.isEmpty(password)) {
            msg = "用户密码不能为空";
        } else if (StringUtils.isEmpty(phone)) {
            msg = "请输入“手机号”";
        } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            msg = "密码长度必须在5到20个字符之间";
        } else if (userType.equals(UserType.getKeyByType("企业用户")) && StringUtils.isEmpty(deptName)) {
            msg = "企业名称不能为空";
        } else if (userType.equals(UserType.getKeyByType("企业用户")) && sysDeptService.checkDeptNameExist(deptName)  > 0) {
            msg = "企业已被注册，有疑问请联系工作人员";
        } else if (phone != null && phone.length() != 0 && !userService.checkPhoneUnique(sysUser)) {
            msg = "手机号已存在，请勿重复注册";
        } else {
            Long deptId = 0L;
            // 企业用户
            if (userType.equals(UserType.getKeyByType("企业用户"))) {
                // 新建"企业"
                SysDept sysDept = new SysDept();
                sysDept.setParentId(DeptType.getIdByType("企业用户"));
                sysDept.setAncestors(DeptAncestors.getAncestors("企业用户"));
                sysDept.setDeptName(deptName);
                sysDept.setPhone(phone);
                sysDept.setEmail(email);
                sysDept.setStatus("0");
                sysDept.setDelFlag("0");
                sysDept.setCreateTime(new Date());
                sysDeptService.insertDept(sysDept);
                // 新建的企业人员数据
                deptId = sysDept.getDeptId();
                List<SysRoleDept> sysRoleDeptList = new ArrayList<>();
                //企业拥有者
                SysRoleDept sysRoleDeptContro = new SysRoleDept();
                sysRoleDeptContro.setRoleId(RoleConstants.ROLE_ID_COMPANY_Contro);
                sysRoleDeptContro.setDeptId(deptId);
                sysRoleDeptList.add(sysRoleDeptContro);
                // 企业管理员
                SysRoleDept sysRoleDeptAdmin = new SysRoleDept();
                sysRoleDeptAdmin.setRoleId(RoleConstants.ROLE_ID_COMPANY_ADMIN);
                sysRoleDeptAdmin.setDeptId(deptId);
                sysRoleDeptList.add(sysRoleDeptAdmin);
                // 企业检测员
                SysRoleDept sysRoleDeptTester = new SysRoleDept();
                sysRoleDeptTester.setRoleId(RoleConstants.ROLE_ID_COMPANY_TEST);
                sysRoleDeptTester.setDeptId(deptId);
                sysRoleDeptList.add(sysRoleDeptTester);
                // 批量添加
                sysRoleDeptService.insertRoleDepts(sysRoleDeptList);
            }
            // 个人用户
            if (userType.equals(UserType.getKeyByType("个人用户"))) {
                deptId = DeptType.getIdByType("个人用户");
            }
            // 新建用户
            sysUser.setDeptId(deptId);
            boolean regFlag = userService.registerUser(sysUser);
            if (!regFlag)
            {
                msg = "注册失败,请联系系统管理人员";
            }
            else
            {
                // 注册成功后，绑定：用户-角色
                Long roleId = 0L;
                if (userType.equals(UserType.getKeyByType("个人用户"))) {
                    roleId = RoleIdEnum.getRoleId("个人用户");
                    sysRoleDeptService.insertAuthUsers(roleId, new Long[]{sysUser.getUserId()});
                } else if (userType.equals(UserType.getKeyByType("企业用户"))) {
                    roleId = RoleIdEnum.getRoleId("企业系统管理员");
                    sysRoleDeptService.insertAuthUsers(roleId, new Long[]{sysUser.getUserId()});
                    roleId = RoleIdEnum.getRoleId("企业账号拥有者");
                    sysRoleDeptService.insertAuthUsers(roleId, new Long[]{sysUser.getUserId()});
                    roleId = RoleIdEnum.getRoleId("检测员");
                    sysRoleDeptService.insertAuthUsers(roleId, new Long[]{sysUser.getUserId()});
                }
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(sysUser.getPhonenumber() == null ? sysUser.getPhonenumber() : sysUser.getEmail(), Constants.REGISTER, MessageUtils.message("user.register.success")));
            }
        }
        return msg;
    }

    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new CaptchaException();
        }
    }
}
